package com.sx.wechat.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sx.core.model.Information;
import com.sx.core.model.Order;
import com.sx.core.mybatis.SessionTemplate;
import com.sx.core.utils.JwtUtils;
import com.sx.core.utils.PropertyUtils;
import com.sx.core.utils.UUIDUtils;
import com.sx.core.utils.WxJsUtils;
import com.sx.core.utils.WxRequestInstance;
import com.sx.core.vo.JsonReaderResponse;
import com.sx.core.vo.Params;
import com.sx.wechat.security.Principal;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lihao on 2018/11/29.
 */
@Service("orderService")
public class OrderService {
    Log logger= LogFactory.getLog(getClass());
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    @Autowired
    SessionTemplate sessionTemplate;
    
    @Autowired
    ThreadPoolTaskExecutor executor;

    String template2= PropertyUtils.getProperty("wx.template2");
    
    @Transactional
    public JsonReaderResponse sub_order(JSONObject params,String teacherid){
        String orderid= UUIDUtils.generateUuid32();
        String labid=params.getString("labid");
        String year=params.getString("year");
        String month=params.getString("month");
        String week=params.getString("week");
        String lessonid=params.getString("lessonid");
        String remark=params.getString("remark");
        String regionid=params.getString("regionid");
        String weekday=params.getString("weekday");
        String day=params.getString("day");
        String dateformat=params.getString("dateformat");
        String contentid=params.getString("contentid");
        Order order=sessionTemplate.get(Order.class,"selectExist",new Params().p("regionid",regionid).p("year",year).p("month",month).p("day",day).p("labid",labid));
        if(order!=null){
            return new JsonReaderResponse("该实验室已被预订，无法预约",101);
        }

        Map lessons=jdbcTemplate.queryForMap("select * from t_lesson WHERE id=?",lessonid);
        Map region=jdbcTemplate.queryForMap("select * from t_region WHERE id=?",regionid);
        Map lab=jdbcTemplate.queryForMap("select * from t_laboratory WHERE id=?",labid);
        Information teacher=sessionTemplate.get(Information.class,teacherid);

        if(!StringUtils.equals(lessons.get("creator").toString(),teacher.getId())){
            jdbcTemplate.update("UPDATE t_lesson SET yy=yy+1 WHERE id=?",lessonid);
        }

        order=new Order();
        order.setTime(new Date());
        order.setId(orderid);
        order.setLabid(labid);
        order.setYear(year);
        order.setMonth(month);
        order.setWeek(week);
        order.setWeekday(weekday);
        order.setLessonid(lessonid);
        order.setRemark(remark);
        order.setRegionid(regionid);
        order.setTeacherid(teacherid);
        order.setDay(day);
        order.setLessonname(ObjectUtils.toString(lessons.get("name")));
        order.setRegionname(ObjectUtils.toString(region.get("name")));
        order.setLabname(ObjectUtils.toString(lab.get("name")));
        order.setTeachername(teacher.getName());
        order.setContentid(contentid);

        String rg=ObjectUtils.toString(region.get("region"));
        String[] s_e=rg.split("[-]");

        try {
            Date start= DateUtils.parseDate(dateformat+" "+s_e[0],new String[]{"yyyy-MM-dd HH:mm"});
            Date end= DateUtils.parseDate(dateformat+" "+s_e[1],new String[]{"yyyy-MM-dd HH:mm"});
            order.setStartdate(start);
            order.setEnddate(end);
            order.setYutime(dateformat);

        } catch (ParseException e) {
            e.printStackTrace();
        }


        sessionTemplate.save(order);
        JSONArray students=null;
        try{
            students= params.getJSONArray("students");
        }catch (Exception e){
            students= JSON.parseArray(params.getString("students"));
        }


        List<String> ids=new ArrayList<>();
        String sql="insert into t_order_rec_stu (id,orderid,stuid,classid) values (?,?,?,?)";
        for(int i=0;i<students.size();i++){
            JSONObject jsonObject=students.getJSONObject(i);
            jdbcTemplate.update(sql,UUIDUtils.generateUuid32(),orderid,jsonObject.get("stuid"),jsonObject.get("classid"));
            ids.add(jsonObject.getString("stuid"));
        }
        executor.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    push(teacher,lessons,region,lab,ids,orderid);
                }catch (Exception e){
                    logger.error(e);
                }
            }
        });
        return new JsonReaderResponse();
    }
    private void push(Information teacher,Map lessons,Map region,Map lab,List<String> students,String orderid){
        //教师推送
        WxJsUtils.Template tem = new WxJsUtils.Template();
        String url="http://v1.scnetview.com/vrmobile/msg.html?id=%s&orderid=%s&isdirectly=true&token=%s";

        Principal principal=new Principal();
        principal.setBindno(teacher.getSno());
        principal.setId(teacher.getId());
        principal.setType(teacher.getType());
        String sub_ject= JSON.toJSONString(principal);
        String token= JwtUtils.createJWT(teacher.getId(),sub_ject);
        String lessonid= ObjectUtils.toString(lessons.get("id"));

        tem.setUrl(String.format(url,lessonid,orderid,token));
        Map<String, Object> paras = new HashMap<String, Object>();
        String acctoken= WxRequestInstance.getInstance().getBaseToken();




        if(StringUtils.isNotBlank(teacher.getOpenid())){
            tem.setTemplate_id(template2); // 模版id
            tem.setTopcolor("#00DD00");
            tem.setTouser(teacher.getOpenid());
            paras.put("first", new WxJsUtils.TemplateParam("您的课程已预约成功，请准时参加！", "#F23433"));
            paras.put("keyword1", new WxJsUtils.TemplateParam(ObjectUtils.toString(lessons.get("name")), "#000000"));  // 月份
            paras.put("keyword2", new WxJsUtils.TemplateParam(ObjectUtils.toString(region.get("region")), "#5DB850"));// 应发合计
            paras.put("keyword3", new WxJsUtils.TemplateParam(ObjectUtils.toString(teacher.getName()), "#5DB850")); //扣款合计
            paras.put("keyword4", new WxJsUtils.TemplateParam(ObjectUtils.toString(lab.get("name")), "#5DB850")); // 实发合计
            paras.put("remark", new WxJsUtils.TemplateParam("请准时前往实验室参加课程，谢谢！", "#E4616B"));
            tem.setData(paras);
            WxJsUtils.sendTemplateMsg(acctoken, tem);
        }
        if(students.isEmpty()){
            return;
        }
        List<Map<String,Object>> stus=namedParameterJdbcTemplate.queryForList("select * from t_information where type='1' AND id in(:id)",new Params().p("id",students));
        for(Map<String,Object> stu:stus){
            String op=ObjectUtils.toString(stu.get("openid"));
            if(StringUtils.isEmpty(op)){
                continue;
            }
            paras = new HashMap<String, Object>();
            tem = new WxJsUtils.Template();


            principal=new Principal();
            principal.setBindno(ObjectUtils.toString(stu.get("sno")));
            principal.setId(ObjectUtils.toString(stu.get("id")));
            principal.setType(ObjectUtils.toString(stu.get("type")));
            token= JwtUtils.createJWT(teacher.getId(),JSON.toJSONString(principal));
            tem.setUrl(String.format(url,lessonid,orderid,token));

            tem.setTemplate_id(template2); // 模版id
            tem.setTopcolor("#00DD00");
            tem.setTouser(op);
            paras.put("first", new WxJsUtils.TemplateParam(teacher.getName()+"老师为您预约了课程，请准时参加!", "#F23433"));
            paras.put("keyword1", new WxJsUtils.TemplateParam(ObjectUtils.toString(lessons.get("name")), "#000000"));  // 月份
            paras.put("keyword2", new WxJsUtils.TemplateParam(ObjectUtils.toString(region.get("region")), "#5DB850"));// 应发合计
            paras.put("keyword3", new WxJsUtils.TemplateParam(ObjectUtils.toString(teacher.getName()), "#5DB850")); //扣款合计
            paras.put("keyword4", new WxJsUtils.TemplateParam(ObjectUtils.toString(lab.get("name")), "#5DB850")); // 实发合计
            paras.put("remark", new WxJsUtils.TemplateParam("请准时前往实验室参加课程，谢谢！", "#E4616B"));
            tem.setData(paras);
            WxJsUtils.sendTemplateMsg(acctoken, tem);
        }
    }
    //发送成绩通知模板

    /**
     * 模版ID：ySHoWkamvsvJJTGxLWcKbUIIsUwLy5IpUFtCj0WlPww
     详细内容：
     {{first.DATA}}
     实训成绩：{{keyword1.DATA}}
     实训课程：{{keyword2.DATA}}
     实训时间：{{keyword3.DATA}}
     实训地点：{{keyword4.DATA}}
     {{remark.DATA}}

     李达您好，您的实训成绩已经统计完成！
     实训成绩：90分
     实训课程：监狱实训
     实训时间：20181204 10:00
     实训地点：实训室1
     点击查看详情（蓝色）

     */
    public void pushScore(Information student,Double score,String lessonid,String orderid,String lessonname,String labname,String startDate){
        //教师推送
        WxJsUtils.Template tem = new WxJsUtils.Template();
        Map<String, Object> paras = new HashMap<String, Object>();
        String acctoken= WxRequestInstance.getInstance().getBaseToken();
        if(StringUtils.isNotBlank(student.getOpenid())){
            tem.setTemplate_id("ySHoWkamvsvJJTGxLWcKbUIIsUwLy5IpUFtCj0WlPww"); // 模版id
            tem.setTopcolor("#00DD00");
            tem.setTouser(student.getOpenid());
            Principal principal=new Principal();
            principal.setBindno(ObjectUtils.toString(student.getSno()));
            principal.setId(ObjectUtils.toString(student.getId()));
            principal.setType(ObjectUtils.toString(student.getType()));
            String token= JwtUtils.createJWT(student.getId(),JSON.toJSONString(principal));
            String url="http://v1.scnetview.com/vrmobile/record.html?id=%s&orderid=%s&token=%s";
            tem.setUrl(String.format(url,lessonid,orderid,token));
            paras.put("first", new WxJsUtils.TemplateParam(student.getName()+"您好，您的实训成绩已经统计完成！", "#F23433"));
            paras.put("keyword1", new WxJsUtils.TemplateParam(score+"分", "#000000"));  // 月份
            paras.put("keyword2", new WxJsUtils.TemplateParam(lessonname, "#5DB850"));// 应发合计
            paras.put("keyword3", new WxJsUtils.TemplateParam(startDate, "#5DB850")); //扣款合计
            paras.put("keyword4", new WxJsUtils.TemplateParam(labname, "#5DB850")); // 实发合计
            paras.put("remark", new WxJsUtils.TemplateParam("点击查看详情！", "#E4616B"));
            tem.setData(paras);
            WxJsUtils.sendTemplateMsg(acctoken, tem);
        }

    }
}
